package com.pet.shop.service.room;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.pet.exceptions.BusinessException;
import com.pet.shop.dto.PageDto;
import com.pet.shop.entity.room.Monitor;
import com.pet.shop.mappers.room.MonitorMapper;
import com.pet.shop.utils.YsApiResult;
import com.pet.shop.utils.YsDeviceApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class MonitorServiceImpl implements IMonitorService {

    protected static final Logger logger = LoggerFactory.getLogger(MonitorServiceImpl.class);

    @Autowired
    private MonitorMapper monitorMapper;

    @Override
    public int deleteEntity(Long id) {
        Monitor monitor = monitorMapper.get(id);
        if(monitor == null) return 0;
        YsApiResult result = YsDeviceApi.deleteDevice(MonitorAppUtil.getMonitorApp().getAccessToken(), monitor.getSn());
        logger.info("删除设备：{}， {}", monitor.getSn(), result);
        return monitorMapper.delete(id);
    }

    @Override
    public int deleteEntityList(List<Long> idList) {
        if(idList == null || idList.isEmpty()) return 0;
        int i = 0;
        for (Long id : idList) {
            i += deleteEntity(id);
        }
        return i;
    }

    @Override
    public Monitor insertEntity(Monitor monitor) {
        if(monitor == null){
            throw new BusinessException("设备信息不能为空");
        }
        if(StringUtils.isEmpty(monitor.getSn())){
            throw new BusinessException("设备号不能为空");
        }
        Monitor serverSn = monitorMapper.queryBySn(monitor.getSn());
        if(serverSn != null){
            throw new BusinessException("设备号已存在");
        }

        YsApiResult result = YsDeviceApi.addDevice(MonitorAppUtil.getMonitorApp().getAccessToken(), monitor.getSn(), monitor.getValidateCode());

        //20017 设备已被自己添加
        if(!result.getCode().equals(YsApiResult.SUCCESS) && !result.getCode().equals("20017")){
            throw new BusinessException(result.getMsg() + " (" + result.getCode() + ")");
        }
        result = YsDeviceApi.offDeviceEncrypt(MonitorAppUtil.getMonitorApp().getAccessToken(), monitor.getSn(), monitor.getValidateCode());
        logger.info("关闭设备加密设置：{}， {}", monitor.getSn(), result);
        monitor.setCreateTime(new Date());
        monitor.setStatus(0);
        monitorMapper.insert(monitor);
        return monitor;
    }

    @Override
    public Monitor getEntity(Long id) {
        return monitorMapper.get(id);
    }

    @Override
    public int updateEntity(Monitor record) {
        Monitor serverSn = monitorMapper.get(record.getId());
        if(serverSn == null){
            throw new BusinessException("设备不存在");
        }
        if(!StringUtils.isEmpty(record.getSn()) && !record.getSn().equalsIgnoreCase(serverSn.getSn())){
            throw new BusinessException("不允许修改设备号");
        }

        return monitorMapper.update(record);
    }

    @Override
    public PageDto<Monitor> queryPage(PageDto<Monitor> pageDto) {
        Page<Monitor> page = monitorMapper.queryPage(pageDto);
        pageDto.setPageResult(page);
        return pageDto;
    }

    @Override
    public Monitor checkMonitorVideo(Long monitorId) {
        Monitor monitor = monitorMapper.get(monitorId);
        if(monitor == null){
            throw new BusinessException("设备不存在");
        }
        JSONObject resultJson = YsDeviceApi.getLappLiveAddress(MonitorAppUtil.getMonitorApp().getAccessToken(), monitor.getSn());
        String code = resultJson.getString("code");
        if(!YsApiResult.SUCCESS.equals(code)){
            throw new BusinessException(resultJson.getString("msg"));
        }
        JSONObject dataJson = resultJson.getJSONObject("data");
        int status = dataJson.getIntValue("status");
        monitor.setStatus(status);
        if(status == 0){
            monitorMapper.update(monitor);
            throw new BusinessException("设备未使用或直播已关闭");
        }
        String liveAddress = dataJson.getString("liveAddress");
        monitor.setStatus(status);
        monitor.setVideoAddress(liveAddress);
        monitorMapper.update(monitor);
        return monitor;
    }
}
